/*
 * 统一定义接口请求
 * @Author: Chenliang(930225)
 * @Date: 2019-10-11 14:38:14
 * @LastEditors  : Chenliang(930225)
 * @LastEditTime : 2020-01-19 12:39:45
 */

import fetch from 'dva/fetch';
const sdpAppId = '5d6553a2-a559-4c29-9fa5-ad45ab339f1c';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.name = response.status;
  error.response = response;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  const newOptions = {
    ...options
  };
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'PATCH' ||
    newOptions.method === 'DELETE'
  ) {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
  }
  newOptions.headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    "Authorization": newOptions.Auth,
    'sdp-app-id': sdpAppId,
    ...newOptions.headers,
  };

  return fetch(url, newOptions)
    .then(response => {
      checkStatus(response);
      return response.json();
    })
    .then(data => {
      const ret = {
        data,
        headers: {},
      };
      return ret;
    }).catch(e => {
      console.log('接口错误：', e)
    });
}
